package com.cxh.rmsq.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.cxh.rmsq.common.IntentExtra;
import com.cxh.rmsq.model.qrcode.QrCodeDisplayType;
import com.cxh.rmsq.ui.activity.self.LoginPcActivity;
import com.cxh.rmsq.utils.CheckPermissionUtils;
import com.cxh.rmsq.utils.CustomPermissionUtil;
import com.cxh.rmsq.utils.log.SLog;
import com.cxh.rmsq.utils.permission.AppPermissionUtil;
import com.cxh.rmsq.wx.WXManager;

import com.cxh.rmsq.R;

import com.cxh.rmsq.ui.dialog.CommonDialog;

import java.util.ArrayList;

import io.rong.imkit.RongIM;

/**
 * 添加朋友界面
 */
public class AddFriendActivity extends TitleBaseActivity implements View.OnClickListener {
    private static final String TAG = "AddFriendActivity";
    private static final int REQUEST_PERMISSION_ADD_CONTACT_FREIND = 2001;
    private static final int REQUEST_PERMISSION_INVITE_CONTACT_FRIEND = 2002;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getTitleBar().setTitle(R.string.new_friend_title);

        setContentView(R.layout.main_activity_new_friend);
        initView();
    }

    private void initView() {
        findViewById(R.id.create_group).setOnClickListener(this);
        findViewById(R.id.add_friend_tv_search_friend).setOnClickListener(this);
        findViewById(R.id.add_friend_tv_my_qrcode).setOnClickListener(this);
//        findViewById(R.id.add_friend_ll_add_from_contact).setOnClickListener(this);
        findViewById(R.id.add_friend_ll_scan).setOnClickListener(this);
        findViewById(R.id.add_friend_ll_add_from_wechat).setOnClickListener(this);
        findViewById(R.id.add_friend_ll_invite_from_contact).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.create_group:
                Intent intent = new Intent(this, SelectCreateGroupActivity.class);
                startActivityForResult(intent, REQUEST_START_GROUP);
                break;
            case R.id.add_friend_tv_search_friend:
                toSearchFriend();
                break;
            case R.id.add_friend_tv_my_qrcode:
                showMyQRCode();
                break;
//            case R.id.add_friend_ll_add_from_contact:
//                addFriendFromContact();
//                break;
            case R.id.add_friend_ll_scan:
                toScanQRCode();
                break;
            case R.id.add_friend_ll_add_from_wechat:
                inviteWechatFriend();
                break;
            case R.id.add_friend_ll_invite_from_contact:
                inviteFromContact(true);
                break;
        }
    }

    private static final int REQUEST_START_GROUP = 1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_START_GROUP:
                    ArrayList<String> memberList =
                            data.getStringArrayListExtra(IntentExtra.LIST_STR_ID_LIST);
                    SLog.i(TAG, "memberList.size = " + memberList.size());
                    Intent intent = new Intent(this, CreateGroupActivity.class);
                    intent.putExtra(IntentExtra.LIST_STR_ID_LIST, memberList);
                    startActivity(intent);
                    break;
                case 100: //qrCode
                    String qrCode = data.getStringExtra("qrCode").split("=")[1];
                    SLog.i("qrCode", qrCode);
                    startActivity(new Intent(this, LoginPcActivity.class)
                            .putExtra("qrCode", qrCode));
                default:
                    break;
            }
        }
    }

    /**
     * 通过手机号/SealTalk号查找好友
     */
    private void toSearchFriend() {
        Intent intent = new Intent(this, SearchFriendActivity.class);
        startActivity(intent);
    }

    /**
     * 显示我的二维码
     */
    private void showMyQRCode() {
        Intent qrCodeIntent = new Intent(this, QrCodeDisplayWindowActivity.class);
        qrCodeIntent.putExtra(IntentExtra.STR_TARGET_ID, RongIM.getInstance().getCurrentUserId());
        qrCodeIntent.putExtra(IntentExtra.SERIA_QRCODE_DISPLAY_TYPE, QrCodeDisplayType.PRIVATE);
        startActivity(qrCodeIntent);
    }

    /**
     * 从通讯录添加好友
     */
    private void addFriendFromContact() {
        boolean hasPermissions =
                CheckPermissionUtils.requestPermissions(
                        this,
                        new String[]{Manifest.permission.READ_CONTACTS},
                        REQUEST_PERMISSION_ADD_CONTACT_FREIND);
        if (hasPermissions) {
            Intent intent = new Intent(this, AddFriendFromContactActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 扫一扫
     */
    private void toScanQRCode() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//            // 显示对话框告知用户权限使用目的
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("权限申请")
                    .setMessage("为了便于您使用扫码功能，我们需要访问您的相机权限。")
                    .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Dialog permissionInfoDialog = new Dialog(AddFriendActivity.this);
                            //应用上架要求添加权限使用说明
                            String permissionInfoTitle = "";
                            String permissionInfoContent = "";
                            permissionInfoTitle = getResources().getString(R.string.permission_info_title_camera);
                            permissionInfoContent = getResources().getString(R.string.permission_info_content_camera);
                            if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(permissionInfoContent)) {
                                CustomPermissionUtil.showPermissionInfo(AddFriendActivity.this
                                        , permissionInfoDialog, permissionInfoTitle, permissionInfoContent);
                            }
                            AppPermissionUtil.requestPermissions(AddFriendActivity.this, new String[]{Manifest.permission.CAMERA}, new AppPermissionUtil.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    if (!checkHasStoragePermission()) {
                                        return;
                                    }
                                    Intent intent = new Intent(AddFriendActivity.this, ScanActivity.class);
                                    startActivity(intent);
                                    permissionInfoDialog.dismiss();
                                }

                                @Override
                                public void onPermissionDenied() {
                                    permissionInfoDialog.dismiss();
                                }
                            });
                        }
                    })
                    .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 用户拒绝权限申请
                        }
                    })
                    .show();
        } else {
            // 已获得权限，执行相关操作
            if (!checkHasStoragePermission()) {
                return;
            }
            startActivityForResult(new Intent(this, ScanActivity.class), 100);
        }

    }
    public static final int REQUEST_CODE_ASK_PERMISSIONS = 100;

    private boolean checkHasStoragePermission() {
        // 从6.0系统(API 23)开始，访问外置存储需要动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission = checkSelfPermission(Manifest.permission.CAMERA);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                        new String[] {Manifest.permission.CAMERA},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return false;
            }
        }
        return true;
    }
    /**
     * 微信邀请好友
     */
    private void inviteWechatFriend() {
        CommonDialog commonDialog =
                new CommonDialog.Builder()
                        .setTitleText(R.string.new_friend_invite_wechat_friend)
                        .setContentMessage(
                                getString(R.string.new_friend_invite_wechat_friend_dialog_content))
                        .setDialogButtonClickListener(
                                new CommonDialog.OnDialogButtonClickListener() {
                                    @Override
                                    public void onPositiveClick(View v, Bundle bundle) {
                                        WXManager.getInstance().inviteToSealTalk();
                                    }

                                    @Override
                                    public void onNegativeClick(View v, Bundle bundle) {
                                    }
                                })
                        .build();
        commonDialog.show(getSupportFragmentManager(), null);
    }

    /**
     * 从通讯录邀请好友
     */
    private void inviteFromContact(boolean needCheckPermission) {
        boolean hasPermissions = true;
        if (needCheckPermission) {
            hasPermissions =
                    CheckPermissionUtils.requestPermissions(
                            this,
                            new String[]{Manifest.permission.READ_CONTACTS},
                            REQUEST_PERMISSION_INVITE_CONTACT_FRIEND);
        }
        if (hasPermissions) {
            Intent intent = new Intent(this, InviteFriendFromContactActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 跳转到请求通讯录说明界面
     */
    private void toRequestContactPermission() {
        Intent intent = new Intent(this, RequestContactPermissionActivity.class);
        startActivity(intent);
    }


    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSION_ADD_CONTACT_FREIND
                || requestCode == REQUEST_PERMISSION_INVITE_CONTACT_FRIEND) {
            boolean grandResult = true;
            int length = permissions.length;
            for (int i = 0; i < length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    grandResult = false;
                    break;
                }
            }
            if (grandResult) {
                if (requestCode == REQUEST_PERMISSION_ADD_CONTACT_FREIND) {
                    addFriendFromContact();
                } else if (requestCode == REQUEST_PERMISSION_INVITE_CONTACT_FRIEND) {
                    inviteFromContact(false);
                }
            } else {
                toRequestContactPermission();
            }
        }
    }
}
